import React, { useEffect } from 'react'
import type { FC, ReactNode } from 'react'
import styled from 'styled-components'
import { Editor } from '@bytemd/react'
import zh_Hans from 'bytemd/locales/zh_Hans.json'

import { useMyDispatch, useMySelector, MyShallEqual } from '../../store'
import { setMdContent } from '../../store/modules/success'

// 实现解析gfm语法
import gfm from '@bytemd/plugin-gfm'

// 实现代码高亮
import highlight from '@bytemd/plugin-highlight'
import 'highlight.js/styles/monokai-sublime.css'

// 实现解析前辅文
import frontmatter from '@bytemd/plugin-frontmatter'

// 实现解析数学公式
import math from '@bytemd/plugin-math'

// 实现解析流程图
import mermaid from '@bytemd/plugin-mermaid'

// 实现解析Gemoji表情
import gemoji from '@bytemd/plugin-gemoji'

import 'bytemd/dist/index.css'
import './index.scss'

// 定义 Wrap 组件
const Wrap = styled.div`
  /* 添加样式 */
  .bytemd {
    height: 400px;
    width: 1100px;
    background-color: #242424;
  }
`

const plugins = [gfm(), highlight(), frontmatter(), math(), mermaid(), gemoji()]

interface IProps {
  children?: ReactNode
}

const MarkDownEditor: FC<IProps> = () => {
  const { mdContent } = useMySelector(
    (state) => ({
      mdContent: state.success.mdContent
    }),
    MyShallEqual
  )
  const dispatch = useMyDispatch()
  useEffect(() => {
    console.log(mdContent)
  }, [mdContent])

  const onChange = (v: string) => {
    dispatch(setMdContent(v))
  }

  return (
    <Wrap>
      <Editor
        value={mdContent}
        onChange={onChange}
        locale={zh_Hans}
        plugins={plugins}
      />
    </Wrap>
  )
}

export default MarkDownEditor
